<template>
  <el-form ref="formRef" :model="form" :rules="formOption.rules" label-width="150px">
    <el-form-item :label="`${connect_type.show_name}:`" :prop="intact_prop" class="!hidden">
      <el-radio-group v-model="form[intact_prop]" class="ml-4">
        <el-radio
          v-for="(item, index) in connect_type.option"
          :key="'connect_type' + index"
          :label="item.req_val"
        >
          {{ item.show_val }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
    <template v-if="form[intact_prop] && props.option[form[intact_prop]].constructor === Object">
      <el-form-item
        :label="`${props.option[form[intact_prop]].show_name}:`"
        :prop="props.option[form[intact_prop]].req_name"
        :rules="
          props.option[form[intact_prop]].is_required.includes(props.sqlName)
            ? [
                {
                  required: true,
                  message: props.option[form[intact_prop]].input_info,
                  trigger: 'blur'
                }
              ]
            : []
        "
      >
        <ns-input
          v-model="form[props.option[form[intact_prop]].req_name]"
          :rows="3"
          type="textarea"
          :show-password="props.option[form[intact_prop]].show_name == 'IP地址'"
          :placeholder="props.option[form[intact_prop]].input_info"
        />
      </el-form-item>
    </template>
    <template
      v-else-if="form[intact_prop] && props.option[form[intact_prop]].constructor === Array"
    >
      <el-form-item
        v-for="item in props.option[form[intact_prop]]"
        :key="item.req_name"
        :label="`${item.show_name}:`"
        :prop="item.req_name"
        :rules="
          item.is_required.includes(props.sqlName)
            ? [
                {
                  required: true,
                  message: `${item.show_name}不能为空`,
                  trigger: item.input_type === 'input' ? 'blur' : 'change'
                }
              ]
            : []
        "
      >
        <ns-input
          @input="(value) => handleInputChange(value, item.req_name)"
          v-if="item.input_type === 'input'"
          v-model="form[item.req_name]"
          :placeholder="item.input_info"
          :type="item.req_encrypt ? 'password' : 'text'"
          :disabled="disabledArr.includes(item.req_name) && !props.isAdd"
        />
        <el-upload
          v-else-if="item.input_type === 'file'"
          v-model="form[item.req_name]"
          :action="fileUploadOption.action"
          :data="{ path: '/db/' + item.req_name }"
          :drag="fileUploadOption.drag"
          :multiple="fileUploadOption.multiple"
          :limit="fileUploadOption.limit"
          :headers="headers"
          :on-exceed="handleExceed"
          :on-success="(res) => handleUploadSuccess(res, item.req_name)"
          :on-remove="(res) => handleUploadRemove(item.req_name)"
          style="width: 80%"
        >
          <el-button type="primary" bg text :icon="UploadFilled">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="props.option.advance_params" label="高级参数" prop="advanceParams">
        <el-popover :visible="visible" placement="top" :width="440" trigger="click">
          <template #reference>
            <ns-input @click="showAdvance" readonly>
              <template #prefix>
                <el-tag
                  v-for="(item, index) in form.advanceParams"
                  :key="'advanceParams' + index"
                  class="mr2"
                  >{{ index }}:{{ item }}</el-tag
                >
              </template>
            </ns-input>
          </template>
          <div class="mb5">
            <div v-for="(item, index) in advanceGroup" :key="'advanceGroup' + index" class="mb-2">
              <ns-input style="display: inline-block; width: 41%" v-model="item.p_key" />
              :
              <ns-input style="display: inline-block; width: 41%" v-model="item.p_val" />
              <span class="ml-2 v-middle" @click="deleteAdvance(index)">
                <el-icon color="#F56C6C" :size="18"><Remove /></el-icon>
              </span>
              <span
                class="ml-2 v-middle"
                @click="addAdvance"
                v-if="index == advanceGroup.length - 1"
              >
                <el-icon color="#00aeff" :size="18"><CirclePlus /></el-icon>
              </span>
            </div>
          </div>
          <div style="text-align: right">
            <el-button type="primary" plain @click="submitAdvance">确定</el-button>
            <el-button type="danger" @click="cancle">取消</el-button>
          </div>
        </el-popover>
      </el-form-item>
    </template>
  </el-form>
</template>

<script setup>
import cloneDeep from 'lodash-es/cloneDeep'
import { UploadFilled, Remove, CirclePlus } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
const { proxy } = getCurrentInstance()
import { SM4Decrypt } from '@/utils/sm4Util'
import { ElMessage } from 'element-plus'
const paramsChange = ref([])
const props = defineProps({
  option: {
    type: Object,
    default: () => {}
  },
  info: {
    type: Object,
    default: () => {}
  },
  sqlName: {
    type: String,
    default: ''
  },
  isAdd: {
    type: Boolean,
    default: true
  },
  configStatus: {
    type: Function,
    default: () => {}
  },
  defaulePort: {
    type: String,
    default: ''
  }
})
const url = import.meta.env.VITE_UPLOAD_URL
const disabledArr = ref(['ip', 'port'])
const formRef = ref(null)
const visible = ref(false)
const connect_type = computed(() => props.option.connect_type)
const intact_prop = computed(() => props.option.connect_type.req_name)
const headers = ref({ Authorization: 'Bearer ' + getAccessToken() })
const fileUploadOption = reactive({
  action: url,
  drag: false,
  multiple: false,
  limit: 1
})
const handleInputChange = (value, prop) => {
  if (
    prop === 'dbAccount' ||
    prop === 'dbPassword' ||
    prop == 'sshPassword' ||
    prop == 'userName' ||
    prop == 'defaultDbName'
  ) {
    props.configStatus()
  }
}
let form = reactive({
  connectType: 'params',
  advanceParams: {}
})
let advanceGroup = ref([{ p_key: '', p_val: '' }])
const deleteAdvance = (index) => {
  if (advanceGroup.value.length > 1) {
    advanceGroup.value.splice(index, 1)
  }
}
const showAdvance = () => {
  visible.value = true
  paramsChange.value = cloneDeep(advanceGroup.value)
}
const cancle = () => {
  visible.value = false
  advanceGroup.value = cloneDeep(paramsChange.value)
}
const addAdvance = () => {
  if (advanceGroup.value.every((item) => item.p_key !== '' && item.p_val !== '')) {
    advanceGroup.value.push({ p_key: '', p_val: '' })
  } else {
    ElMessage.error('键名和值不能为空')
  }
}
const submitAdvance = () => {
  if (!advanceGroup.value.every((item) => item.p_key !== '' && item.p_val !== '')) {
    ElMessage.error('键名和值不能为空')
    return
  }
  const seen = new Map()
  for (const param of advanceGroup.value) {
    for (const [key, value] of Object.entries(param)) {
      if (key === 'p_key') {
        const keyValuePair = `${key}-${value}`
        if (seen.has(keyValuePair) && value != '') {
          ElMessage.error(`键名${value}重复`)
          return
        }
        seen.set(keyValuePair, true)
      }
    }
  }
  let arr = {}
  for (const k of advanceGroup.value) {
    arr[k.p_key] = k.p_val
  }
  form.advanceParams = arr
  visible.value = false
}
// 上传成功回调
function handleUploadSuccess(res, prop) {
  if (res.code === 200) {
    form[prop] = res.data.path
    formRef.value.validateField(prop)
  }
}
function handleUploadRemove(prop) {
  form[prop] = ''
  formRef.value.validateField(prop)
}
// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${fileUploadOption.limit} 个!`)
}
const formOption = reactive({
  rules: {}
})

watch(
  props.info,
  () => {
    if (!props.isAdd) {
      for (const k in props.info) {
        if (
          k.indexOf('password') > -1 ||
          k.indexOf('Password') > -1 ||
          k.indexOf('dbAccount') > -1 ||
          k.indexOf('userName') > -1
        ) {
          props.info[k] && (form[k] = SM4Decrypt(props.info[k]))
        } else {
          form[k] = props.info[k]
        }
      }
      if (JSON.stringify(form.advanceParams) !== '{}') {
        const arr = []
        for (const k in form.advanceParams) {
          arr.push({ p_key: k, p_val: form.advanceParams[k] })
        }
        advanceGroup.value = arr
      }
    }
  },
  { immediate: true }
)
watch(
  () => props.defaulePort,
  () => {
    if (props.isAdd) {
      form.port = props.defaulePort
    }
  },
  { immediate: true }
)
defineExpose({
  formRef,
  form
})
</script>
<style lang="scss" scoped>
.card {
  background-color: #ecf5ff;
  height: 25px;
  line-height: 25px;
  display: inline-block;
  color: #409eff;
  margin-left: 5px;
  font-size: 12px;
  border-width: 1px solid #d9ecff;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
  padding: 0 10px;
}
</style>
